package com.zenithmind.chat.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zenithmind.chat.mapper.ChatFriendSettingMapper;
import com.zenithmind.chat.pojo.entity.ChatFriendSetting;
import com.zenithmind.chat.pojo.dto.ChatFriendSettingDTO;
import com.zenithmind.chat.pojo.vo.ChatFriendSettingVO;
import com.zenithmind.chat.service.ChatFriendSettingService;
import com.zenithmind.common.exception.BusinessException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 好友设置服务实现类 - 遵循单一职责原则
 * 只负责好友设置的业务逻辑处理
 *
 * @author ZenithMind Team
 * @since 2025-01-09
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class ChatFriendSettingServiceImpl extends ServiceImpl<ChatFriendSettingMapper, ChatFriendSetting> 
        implements ChatFriendSettingService {

    private final ChatFriendSettingMapper chatFriendSettingMapper;

    @Override
    public ChatFriendSettingVO getFriendSetting(String userId, String friendId) {
        LambdaQueryWrapper<ChatFriendSetting> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ChatFriendSetting::getUserId, userId)
               .eq(ChatFriendSetting::getFriendId, friendId);
        
        ChatFriendSetting setting = getOne(wrapper);
        if (setting == null) {
            // 创建默认设置
            String settingId = createDefaultSetting(userId, friendId);
            setting = getById(settingId);
        }
        
        return convertToVO(setting);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateFriendSetting(ChatFriendSettingDTO dto, String userId) {
        LambdaQueryWrapper<ChatFriendSetting> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ChatFriendSetting::getUserId, userId)
               .eq(ChatFriendSetting::getFriendId, dto.getFriendId());
        
        ChatFriendSetting setting = getOne(wrapper);
        if (setting == null) {
            throw new BusinessException("好友设置不存在");
        }

        // 更新设置
        setting.setRemark(dto.getRemark());
        setting.setGroupName(dto.getGroupName());
        setting.setIsMuted(booleanToInteger(dto.getIsMuted()));
        setting.setIsTop(booleanToInteger(dto.getIsTop()));
        setting.setIsBlocked(booleanToInteger(dto.getIsBlocked()));
        setting.setUpdateBy(userId);
        setting.setUpdateTime(LocalDateTime.now());

        boolean result = updateById(setting);
        
        if (result) {
            log.info("更新好友设置成功，用户ID: {}, 好友ID: {}", userId, dto.getFriendId());
        }
        
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String createDefaultSetting(String userId, String friendId) {
        ChatFriendSetting setting = new ChatFriendSetting();
        setting.setUserId(userId);
        setting.setFriendId(friendId);
        setting.setRemark("");
        setting.setGroupName("默认分组");
        setting.setIsMuted(0);
        setting.setIsTop(0);
        setting.setIsBlocked(0);
        setting.setCreateBy(userId);
        setting.setCreateTime(LocalDateTime.now());

        save(setting);
        
        log.info("创建默认好友设置成功，用户ID: {}, 好友ID: {}", userId, friendId);
        return setting.getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteFriendSetting(String userId, String friendId) {
        LambdaQueryWrapper<ChatFriendSetting> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ChatFriendSetting::getUserId, userId)
               .eq(ChatFriendSetting::getFriendId, friendId);
        
        boolean result = remove(wrapper);
        
        if (result) {
            log.info("删除好友设置成功，用户ID: {}, 好友ID: {}", userId, friendId);
        }
        
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean batchCreateDefaultSettings(String userId, List<String> friendIds) {
        if (CollectionUtils.isEmpty(friendIds)) {
            return true;
        }

        List<ChatFriendSetting> settings = friendIds.stream()
                .map(friendId -> {
                    ChatFriendSetting setting = new ChatFriendSetting();
                    setting.setUserId(userId);
                    setting.setFriendId(friendId);
                    setting.setRemark("");
                    setting.setGroupName("默认分组");
                    setting.setIsMuted(0);
                    setting.setIsTop(0);
                    setting.setIsBlocked(0);
                    setting.setCreateBy(userId);
                    setting.setCreateTime(LocalDateTime.now());
                    return setting;
                })
                .collect(Collectors.toList());

        boolean result = saveBatch(settings);
        
        if (result) {
            log.info("批量创建默认好友设置成功，用户ID: {}, 数量: {}", userId, friendIds.size());
        }
        
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean batchDeleteFriendSettings(String userId, List<String> friendIds) {
        if (CollectionUtils.isEmpty(friendIds)) {
            return true;
        }

        LambdaQueryWrapper<ChatFriendSetting> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ChatFriendSetting::getUserId, userId)
               .in(ChatFriendSetting::getFriendId, friendIds);
        
        boolean result = remove(wrapper);
        
        if (result) {
            log.info("批量删除好友设置成功，用户ID: {}, 数量: {}", userId, friendIds.size());
        }
        
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateFriendRemark(String userId, String friendId, String remark) {
        LambdaQueryWrapper<ChatFriendSetting> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ChatFriendSetting::getUserId, userId)
               .eq(ChatFriendSetting::getFriendId, friendId);
        
        ChatFriendSetting setting = getOne(wrapper);
        if (setting == null) {
            // 创建默认设置
            createDefaultSetting(userId, friendId);
            setting = getOne(wrapper);
        }

        setting.setRemark(remark);
        setting.setUpdateBy(userId);
        setting.setUpdateTime(LocalDateTime.now());

        boolean result = updateById(setting);
        
        if (result) {
            log.info("更新好友备注成功，用户ID: {}, 好友ID: {}, 备注: {}", userId, friendId, remark);
        }
        
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateFriendGroup(String userId, String friendId, String groupName) {
        LambdaQueryWrapper<ChatFriendSetting> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ChatFriendSetting::getUserId, userId)
               .eq(ChatFriendSetting::getFriendId, friendId);
        
        ChatFriendSetting setting = getOne(wrapper);
        if (setting == null) {
            createDefaultSetting(userId, friendId);
            setting = getOne(wrapper);
        }

        setting.setGroupName(groupName);
        setting.setUpdateBy(userId);
        setting.setUpdateTime(LocalDateTime.now());

        return updateById(setting);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateMuteSetting(String userId, String friendId, Boolean isMuted) {
        LambdaQueryWrapper<ChatFriendSetting> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ChatFriendSetting::getUserId, userId)
               .eq(ChatFriendSetting::getFriendId, friendId);
        
        ChatFriendSetting setting = getOne(wrapper);
        if (setting == null) {
            createDefaultSetting(userId, friendId);
            setting = getOne(wrapper);
        }

        setting.setIsMuted(booleanToInteger(isMuted));
        setting.setUpdateBy(userId);
        setting.setUpdateTime(LocalDateTime.now());

        return updateById(setting);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateTopSetting(String userId, String friendId, Boolean isTop) {
        LambdaQueryWrapper<ChatFriendSetting> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ChatFriendSetting::getUserId, userId)
               .eq(ChatFriendSetting::getFriendId, friendId);
        
        ChatFriendSetting setting = getOne(wrapper);
        if (setting == null) {
            createDefaultSetting(userId, friendId);
            setting = getOne(wrapper);
        }

        setting.setIsTop(booleanToInteger(isTop));
        setting.setUpdateBy(userId);
        setting.setUpdateTime(LocalDateTime.now());

        return updateById(setting);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateBlockSetting(String userId, String friendId, Boolean isBlocked) {
        LambdaQueryWrapper<ChatFriendSetting> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ChatFriendSetting::getUserId, userId)
               .eq(ChatFriendSetting::getFriendId, friendId);
        
        ChatFriendSetting setting = getOne(wrapper);
        if (setting == null) {
            createDefaultSetting(userId, friendId);
            setting = getOne(wrapper);
        }

        setting.setIsBlocked(booleanToInteger(isBlocked));
        setting.setUpdateBy(userId);
        setting.setUpdateTime(LocalDateTime.now());

        return updateById(setting);
    }

    @Override
    public List<ChatFriendSettingVO> getUserFriendSettings(String userId) {
        LambdaQueryWrapper<ChatFriendSetting> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ChatFriendSetting::getUserId, userId)
               .orderByDesc(ChatFriendSetting::getUpdateTime);
        
        List<ChatFriendSetting> settings = list(wrapper);
        return settings.stream()
                .map(this::convertToVO)
                .collect(Collectors.toList());
    }

    @Override
    public List<ChatFriendSettingVO> getFriendSettingsByGroup(String userId, String groupName) {
        LambdaQueryWrapper<ChatFriendSetting> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ChatFriendSetting::getUserId, userId)
               .eq(ChatFriendSetting::getGroupName, groupName)
               .orderByDesc(ChatFriendSetting::getUpdateTime);
        
        List<ChatFriendSetting> settings = list(wrapper);
        return settings.stream()
                .map(this::convertToVO)
                .collect(Collectors.toList());
    }

    @Override
    public List<ChatFriendSettingVO> getTopFriendSettings(String userId) {
        LambdaQueryWrapper<ChatFriendSetting> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ChatFriendSetting::getUserId, userId)
               .eq(ChatFriendSetting::getIsTop, true)
               .orderByDesc(ChatFriendSetting::getUpdateTime);
        
        List<ChatFriendSetting> settings = list(wrapper);
        return settings.stream()
                .map(this::convertToVO)
                .collect(Collectors.toList());
    }

    @Override
    public List<ChatFriendSettingVO> getMutedFriendSettings(String userId) {
        LambdaQueryWrapper<ChatFriendSetting> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ChatFriendSetting::getUserId, userId)
               .eq(ChatFriendSetting::getIsMuted, true)
               .orderByDesc(ChatFriendSetting::getUpdateTime);
        
        List<ChatFriendSetting> settings = list(wrapper);
        return settings.stream()
                .map(this::convertToVO)
                .collect(Collectors.toList());
    }

    @Override
    public List<ChatFriendSettingVO> getBlockedFriendSettings(String userId) {
        LambdaQueryWrapper<ChatFriendSetting> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ChatFriendSetting::getUserId, userId)
               .eq(ChatFriendSetting::getIsBlocked, true)
               .orderByDesc(ChatFriendSetting::getUpdateTime);
        
        List<ChatFriendSetting> settings = list(wrapper);
        return settings.stream()
                .map(this::convertToVO)
                .collect(Collectors.toList());
    }

    /**
     * 转换为VO对象 - 遵循单一职责原则
     */
    private ChatFriendSettingVO convertToVO(ChatFriendSetting setting) {
        ChatFriendSettingVO vo = new ChatFriendSettingVO();
        vo.setId(setting.getId());
        vo.setUserId(setting.getUserId());
        vo.setFriendId(setting.getFriendId());
        vo.setRemark(setting.getRemark());
        vo.setGroupName(setting.getGroupName());
        vo.setIsMuted(integerToBoolean(setting.getIsMuted()));
        vo.setIsTop(integerToBoolean(setting.getIsTop()));
        vo.setIsBlocked(integerToBoolean(setting.getIsBlocked()));
        vo.setCreateTime(setting.getCreateTime());
        vo.setUpdateTime(setting.getUpdateTime());
        return vo;
    }

    /**
     * Boolean转Integer工具方法
     */
    private Integer booleanToInteger(Boolean value) {
        if (value == null) {
            return 0;
        }
        return value ? 1 : 0;
    }

    /**
     * Integer转Boolean工具方法
     */
    private Boolean integerToBoolean(Integer value) {
        if (value == null) {
            return false;
        }
        return value == 1;
    }
}
